package pers.w.chaptertalk.ui.books;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import pers.w.chaptertalk.MainActivity;
import pers.w.chaptertalk.MyService;
import pers.w.chaptertalk.R;
import pers.w.chaptertalk.ShowAndAddBookActivity;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.reader.ReaderActivity;
import pers.w.chaptertalk.ui.ListViewAdapter;

public class BooksFragment extends Fragment {

    private BooksViewModel booksViewModel;
    private MainActivity activity;
    private List<BookInfo> books;
    private View root;
    private String noticeTitle = "公告", notice,webUri=null;

    public void updateAdapter() {
        listViewAdapter.notifyDataSetInvalidated();
    }

    public void startBmpThread() {
        listViewAdapter.startBmpThreads(1);
    }

    private ListViewAdapter listViewAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        booksViewModel =new
                ViewModelProvider(this).get(BooksViewModel.class);
        root = inflater.inflate(R.layout.fragment_books, container, false);
        Tab_Book tbBook = new Tab_Book(root.getContext());
        books = tbBook.get_books();
        setLv_bookrack();
        tbBook.close();
        notice = getString(R.string.server_error);
        TextView tv_notice = root.findViewById(R.id.tv_notice);
        tv_notice.setOnClickListener(v -> Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setTitle(noticeTitle)
                    .setMessage(notice)
                    .setPositiveButton("本帝知道了", null)
                    .create();
            if (webUri!=null){
                dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"前往下载", (dialog1, which) -> {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(webUri);
                    intent.setData(content_url);
                    startActivity(intent);
                });
            }
            dialog.show();
            tv_notice.setBackgroundResource(R.drawable.border);
        }));
        activity = (MainActivity) getActivity();
        assert activity != null;
        if (Fun.isNetworkConnected(root.getContext())) {
            new Thread(() -> {
                final String noticeUri = getString(R.string.server_address) + "notice.php";
                Document doc = null;
                try {
                    doc = Jsoup.connect(noticeUri).get();
                } catch (IOException e) {
                    //e.printStackTrace();
                }

                if (null != doc) {
                    noticeTitle = doc.title();
                    Elements divs = doc.select("div");
                    Element newNotice = divs.get(0);
                     webUri = divs.size()>1?divs.get(1).text():null;
                    Properties properties = new Properties();


                    newNotice.id();
                    notice = newNotice.text().replace(" ", "\n");
                    //判断本地版本
                    activity.runOnUiThread(() -> {
                        boolean error = false;
                        String noticeID = "0";
                        final String fileName = "notice";

                        try {
                            InputStream is = activity.openFileInput(fileName);
                            properties.load(is);
                            noticeID = properties.getProperty("ID", "0");
                            is.close();

                        } catch (IOException e) {
                            error = true;
                        }
                        //出错，或者ID小于服务器，执行
                        if (error || Integer.parseInt(noticeID) < Integer.parseInt(newNotice.id())) {
                            tv_notice.setBackgroundResource(R.drawable.has_new);
                            properties.setProperty("ID", newNotice.id());
                            try {
                                OutputStream out = activity.openFileOutput(fileName, Context.MODE_PRIVATE);
                                properties.store(out, null);
                                out.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    });


                }
            }).start();
        }
        return root;
    }


    private void setLv_bookrack() {
        ListView lv_bookrack = root.findViewById(R.id.lv_bookrack);
        lv_bookrack.setOnItemClickListener((parent, view, position, id) -> {
            Tab_Book tbBook = new Tab_Book(getContext());
            BookInfo bookInfo = books.get(position);
            books.remove(position);
            addBOok(bookInfo);
            tbBook.update_lastReadTime(bookInfo.getID());
            /**/
            Intent intent = new Intent(root.getContext(), ReaderActivity.class);
            Fun.SHARE_MAP.put(R.string.SHARE_READER, bookInfo);
            startActivity(intent);
            tbBook.close();
        });

        lv_bookrack.setOnItemLongClickListener((parent, view, position, id) -> {

            listViewAdapter.on3dotClick((ListViewAdapter.ListItemView) view.getTag());
            return true;
        });
        listViewAdapter = new ListViewAdapter(getContext(), getActivity(), books) {
            @Override
            public void on3dotClick(final ListItemView listItemView) {
                PopupMenu popupMenu = new PopupMenu(root.getContext(), listItemView.name);
                popupMenu.getMenuInflater().inflate(R.menu.operation_bookrack, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(item -> {
                    BookInfo book = listItemView.bookInfo;

                    switch (item.getItemId()) {
                        case R.id.bookrack_showInfo:
                            Intent show_and_add_book = new Intent(root.getContext(), ShowAndAddBookActivity.class);

                            Fun.SHARE_MAP.put(R.string.SHARE_LISTITEM, listItemView);

                            startActivity(show_and_add_book);
                            break;
                        case R.id.bookrack_delete:

                            Tab_Book tbBook = new Tab_Book(root.getContext());
                            //删除所有的缓存文本
                            /*List<Map<String, String>> chapters = tbBook.getTab_chapter().get_chapters(bi.getID());
                            for (Map<String, String> chapter : chapters) {
                                new ChapterInfo(bi.getBookDir(), chapter).delFile();
                            }*/
                            book.delBookDir();
                            tbBook.del(book.getID());
                            book.delBmp();
                            books.remove(book);
                            listViewAdapter.notifyDataSetInvalidated();
                            tbBook.close();
                            break;

                        case R.id.bookrack_cache:
                          int add =  activity.getService().addDownload(book,null);
                            switch(add) {
                                case   MyService.DOWNLOAD_OK:
                                    showToask("开始全本缓存");
                                    break;
                                case  MyService.DOWNLOAD_TOO_MUCH:
                                    showToask("不能同时缓存太多，容易卡顿，最多3本");
                                    break;
                                case  MyService.DOWNLOAD_HAS:
                                    showToask("已经在缓存队列中");
                                    break;
                                case MyService.DOWNLOAD_NODATA:
                                    showToask("没有章节信息，请打开书籍一次");
                                    break;
                            }
                            break;
                        case  R.id.bookrack_stop_cache:
                            activity.getService().stopDownload(book.getID());
                            break;
                    }
                    return true;
                });
                popupMenu.show();
            }
        };
        lv_bookrack.setAdapter(listViewAdapter);
    }

    private void showToask(String msg) {
        Toast.makeText(activity,msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onResume() {//应该接受Activity.OK更好，待优化
        BookInfo bookInfo = (BookInfo) Fun.SHARE_MAP.get(R.string.SHARE_BOOKRACK_ADD);
        if (bookInfo != null) {
            addBOok(bookInfo);
            Fun.SHARE_MAP.remove(R.string.SHARE_BOOKRACK_ADD);
        }
        super.onResume();
    }

    public void addBOok(BookInfo bookInfo) {
        books.add(0, bookInfo);
        listViewAdapter.notifyDataSetInvalidated();
    }

    public List<BookInfo> getBooks() {
        return books;
    }
}
